#!/bin/sh

cd $1

RENDER_XML=`find . -name yafarayRender.xml`

if [ -z "${RENDER_XML}" ]; then
	# Not a Yafaray job
	exit 1
fi

echo "INFO: plugins/render: This (${JOB_ID}) is a Yafaray job" >&2

# Loading configuration
if [ -f ${CASPER_CONF_DIR}/casperd.conf ]; then
	source ${CASPER_CONF_DIR}/casperd.conf
elif [ -f ../../etc/casperd.conf ]; then
	source ../../etc/casperd.conf
fi

export TEXTURES_PATH=${CASPER_WORK_DIR}/${JOB_ID}/textures/
echo "export TEXTURES_PATH=\"${CASPER_WORK_DIR}/${JOB_ID}/textures/\"" >> ${CASPER_WORK_DIR}/${JOB_ID}/variables

mkdir log
for NODE in ${NODES_USE}
do
	mkdir result-${NODE}
done

###################
## PREPARING JOB ##
###################

${CASPER_ROOT_DIR}/scripts/casper-run.sh -l "prepare" -m "preparing" -c "${CASPER_PLUGINS_DIR}/render/prepare.sh ${CASPER_WORK_DIR}/${JOB_ID}" --log "${CASPER_WORK_DIR}/${JOB_ID}/log/prepare.log"
if [ $? -ne 0 ]; then
	echo "ERROR: plugins/render: unable to prepare job ${JOB_ID}" >&2
	exit 1
fi
echo "jobs ${JOB_ID} status prepared"

CURR_DIR=${CASPER_WORK_DIR}/${JOB_ID}

#####################
## RENDERING IMAGE ##
#####################
WAITING=
for i in ${NODES_USE}
do
	${CASPER_ROOT_DIR}/scripts/casper-run.sh -l "render" -m "rendering" -c "yafaray-xml ${CURR_DIR}/yafarayRender-${i}.xml -o ${CURR_DIR}/result-${i}/" --log "${CURR_DIR}/log/render-${i}.log" &
	WAITING="${WAITING} $!"
done
for lock_pid in "${WAITING}"
do
	wait ${lock_pid}
	if [ $? -ne 0 ]; then
		echo "ERROR: plugins/render: unable to get lock for rendering" >&2
		exit 1
	fi
done

for NODE in ${NODES_USE}
do
	if [ ! -f "${CURR_DIR}/result-${NODE}/yafaray.tga" ]; then
		echo "ERROR: plugins/render/execute.sh: unable to find ${CURR_DIR}/result-${NODE}/yafaray.tga" >&2
		exit 1
	fi
done

echo "jobs ${JOB_ID} status rendered"

#########################################
## REBUILDING FINAL IMAGE AND CLEANING ##
#########################################

# Rebuilding image
CMD="convert +append"
for NODE in ${NODES_USE}
do
	CMD="$CMD result-$NODE/yafaray.tga"
done
$CMD ${CASPER_FINAL_DIR}/${JOB_NAME}.tga

exit $?
